<template>
  <XenPageLayout
    title="编辑转正申请"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="编辑转正申请信息"
        :subtitle="`申请单ID: ${probationId || 'P12345'}`"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        :showFooter="false"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @departmentPickerChange="handleDepartmentPickerChange"
        @departmentPickerOpen="handleDepartmentPickerOpen"
        @departmentPickerClose="handleDepartmentPickerClose"
        @autoCompleteChange="handleAutoCompleteChange"
        @autoCompleteSearch="handleAutoCompleteSearch"
      />
    </view>

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen"
      @action="handleFormAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useProbationInfo } from "./composables/useInfo";
// 导入统一事件系统
import { ProbationInfoEvents } from "@/utils/eventBus";
// 导入API和接口类型
import SysHrProbationRequestBillApi from "./api/index";
import type { ISysHrProbationRequestBillVm } from "./api/interface";

// 获取路由参数
const probationId = ref<string>("");

// 创建API实例
const api = SysHrProbationRequestBillApi();

// 审核权限标识
const isMyApprove = ref<boolean>(false);

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 获取编辑页面的表单分组
const formSections = getFormSectionsByPageType("edit");

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "save",
    label: isMyApprove.value ? "取消" : "保存",
    type: "success" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用转正申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  loadProbationDetail,
  search,
  originalData,
  convertFormDataToApiFormatForEdit,
} = useProbationInfo();

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  // XenDynamicFormCard组件会同时触发 @update:model-value 和 @change 事件
  // @update:model-value 已经通过 handleFormDataChange 设置了 formData[fieldKey] = value (部门ID)
  // 这里我们只需要保存部门ID到pickerValues中，用于提交到后端

  // 确保formData中存储的是部门ID（用于组件正确显示选中状态）
  formData[fieldKey] = value;

  // 同时保存到pickerValues中（用于提交到后端）
  pickerValues[fieldKey] = value;

  // 触发验证
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  // 对于自动补全，formData中存储显示文本，pickerValues中存储实际值
  if (option) {
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";
  }

  // 触发验证
  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  // 搜索逻辑已经在组件内部通过searchApi处理
  console.log("搜索:", fieldKey, query);
};

// 获取路由参数
onLoad((options) => {
  if (options?.id) {
    probationId.value = options.id;
  } else {
    uni.showToast({
      title: "缺少ID参数",
      icon: "none",
    });
  }
});

// 页面加载时获取数据
onMounted(async () => {
  // 初始化选项数据
  await initializeOptions();

  // 加载转正申请详情
  if (probationId.value) {
    const result = await loadProbationDetail(probationId.value);
    if (!result.success) {
      uni.showToast({
        title: "加载数据失败",
        icon: "none",
      });
    } else {
      // 保存审核权限标识
      isMyApprove.value = result.isMyApprove || false;
    }
  }
});

// 图片上传处理
const handleImageUpload = async (field: any, event: any) => {
  // 图片上传逻辑
  console.log("图片上传:", field.key, event);
};

const handleImageSuccess = (_field: any, _event: any) => {
  // 图片上传成功处理
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败处理
};

const handleImageDelete = (field: any, event: any) => {
  // 图片删除逻辑
  console.log("图片删除:", field.key, event);
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {
  // 文件上传逻辑
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功处理
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败处理
};

const handleFileDelete = (_field: any, _event: any) => {
  // 文件删除处理
};

// 通用的审核处理方法
const performAudit = async (actionName: string) => {
  const loadingTitle = actionName === "同意" ? "提交中..." : "取消中...";
  uni.showLoading({ title: loadingTitle });

  // 确保有原始数据（包含BillStatus和WorkflowStatus）
  if (!originalData.value) {
    uni.hideLoading();
    uni.showToast({
      title: "缺少原始数据，请重新加载页面",
      icon: "none",
    });
    return;
  }

  // 构造approve接口请求参数
  // 1. 先使用用户编辑的表单数据构造基础Entity
  const editData = convertFormDataToApiFormatForEdit();

  // 2. 然后覆盖状态字段，使用原始数据中的状态信息
  editData.Entity.BillStatus = originalData.value.BillStatus;
  editData.Entity.WorkflowStatus = originalData.value.WorkflowStatus;

  const requestData: ISysHrProbationRequestBillVm = {
    ActionName: actionName,
    Entity: editData.Entity, // 使用用户编辑的数据 + 原始状态字段
    IsMyApprove: isMyApprove.value, // 使用从详情接口获取的审核权限标识
    Remark: null, // 不需要备注弹框
  };

  // 调用approve接口
  const result = await api.approve(requestData);

  uni.hideLoading();

  if (result) {
    // 重新调用search接口获取最新的完整列表数据
    const searchResponse = await search({});
    if (searchResponse && searchResponse.length > 0) {
      // 发送完整列表数据更新事件
      ProbationInfoEvents.emit("refresh", {
        id: result.ID || "",
        data: searchResponse,
        customAction: actionName === "同意" ? "approve" : "reject",
      });
    }

    const successTitle = actionName === "同意" ? "提交成功" : "取消成功";
    uni.showToast({
      title: successTitle,
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
    });
  } else {
    const errorTitle =
      actionName === "同意" ? "提交失败，请重试" : "取消失败，请重试";
    uni.showToast({
      title: errorTitle,
      icon: "none",
    });
  }
};

// 编辑保存方法
const performEdit = async (isSubmit: boolean = false) => {
  const loadingTitle = isSubmit ? "提交中..." : "保存中...";
  uni.showLoading({ title: loadingTitle });

  // 确保有原始数据
  if (!originalData.value) {
    uni.hideLoading();
    uni.showToast({
      title: "缺少原始数据，请重新加载页面",
      icon: "none",
    });
    return;
  }

  // 构造Edit接口请求参数
  const editData = convertFormDataToApiFormatForEdit();

  // 确保使用原始数据中的状态字段
  editData.Entity.BillStatus = originalData.value.BillStatus;
  editData.IsMyApprove = isMyApprove.value; // 使用从详情接口获取的IsMyApprove值

  // 根据操作类型设置WorkflowStatus
  if (isSubmit) {
    // 提交操作：设置WorkflowStatus为"提交中"
    editData.Entity.WorkflowStatus = "提交中";
  } else {
    // 保存操作：使用原始的WorkflowStatus
    editData.Entity.WorkflowStatus = originalData.value.WorkflowStatus;
  }

  // 调用Edit接口
  const result = await api.edit(editData);

  uni.hideLoading();

  if (result) {
    // 重新调用search接口获取最新的完整列表数据
    const searchResponse = await search({});
    if (searchResponse && searchResponse.length > 0) {
      // 发送完整列表数据更新事件
      ProbationInfoEvents.emit("refresh", {
        id: result.ID || "",
        data: searchResponse,
        customAction: isSubmit ? "submit" : "save",
      });
    }

    const successTitle = isSubmit ? "提交成功" : "保存成功";
    uni.showToast({
      title: successTitle,
      icon: "success",
      success: () => {
        if (isSubmit) {
          // 提交成功后跳转页面
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        }
        // 保存成功后不跳转页面
      },
    });
  } else {
    const errorTitle = isSubmit ? "提交失败，请重试" : "保存失败，请重试";
    uni.showToast({
      title: errorTitle,
      icon: "none",
    });
  }
};

// 同意操作
const handleApprove = async () => {
  await performAudit("同意");
};

// 拒绝操作
const handleReject = async () => {
  await performAudit("拒绝");
};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "save":
      handleSaveAction();
      break;
    case "submit":
      handleSubmitAction();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 保存按钮处理方法
const handleSaveAction = async () => {
  if (isMyApprove.value) {
    // 如果IsMyApprove为true，调用拒绝接口
    await handleReject();
  } else {
    // 如果IsMyApprove为false，调用编辑保存接口
    await performEdit(false);
  }
};

// 提交按钮处理方法
const handleSubmitAction = async () => {
  if (isMyApprove.value) {
    // 如果IsMyApprove为true，调用同意接口
    await handleApprove();
  } else {
    // 如果IsMyApprove为false，调用编辑提交接口（WorkflowStatus设为"提交中"）
    await performEdit(true);
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  // 为固定底部按钮预留空间：按钮44px + 上下padding32px + 边框1px + 缓冲15px + 安全区域
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}
</style>
